/**
 * Ant Design of Vue 相关工具类 常用
 */

import { emptyObject } from '@/utils/samsUtil'
import antParam from '@/config/antParameter'

/**
 * Antdv-Table表格 排序对象sorter 转化成后台（spring plus/OrderQueryParam.java）希望接收的数据
 * @param sorter Table表格排序对象sorter
 * @param field  Table表格排序对象sorter的字段  参数为字符串（可以为 columnKey/field）
 * @returns {{pageSorts: []}|{pageSorts: {asc: *, column: *}[]}}    OrderQueryParam.java所接收的数据格式
 */
export function antOrderConvert (sorter = {}, field = null) {
  if (emptyObject(sorter)) {
    return { pageSorts: [] }
  }
  const asc = sorter.order === antParam.orderAsc
  const column = field === antParam.orderColumnKey ? sorter.columnKey : sorter.field
  if (column === undefined || column === null) {
    return { pageSorts: [] }
  }
  return { pageSorts: [{ asc: asc, column: column }] }
}

/**
 * Antdv-Table表格 分页对象pagination 转化成后台（spring plus/QueryParam.java）希望接收的数据
 * @param pagination  Table表格分页对象pagination
 * @returns {{}|{pageIndex: *, pageSize: *}}    QueryParam.java所接收的数据格式
 */
export function antPaginationConvert (pagination = {}) {
  if (emptyObject(pagination)) {
    return {}
  }
  const pageIndex = pagination.current ? pagination.current : antParam.pagingIndex
  const pageSize = pagination.pageSize ? pagination.pageSize : antParam.pagingSize
  return { pageIndex: pageIndex, pageSize: pageSize }
}

/**
 *  分页条件初始化,解决待查询条件时会出现的分页bug
 */
export function initPage (value) {
  value.pageIndex = 1
  value.pageSize = 10
}

/**
 * 部门树Convert字段转换
 *
 * @param treeData
 * @returns {*}
 */
export function treeConvert (treeData) {
  return treeData.map(item => {
    const current = {
      value: item.code,
      title: item.name,
      label: item.level
    }
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // 递归Recursion
      current.children = treeConvert(item.children)
    }
    return current
  })
}

/**
 * 权限树Convert字段转换
 *
 * @param treeData
 * @returns {*}
 */
export function treePermissionConvert (treeData) {
  return treeData.map(item => {
    const current = {
      value: item.id + '',
      title: item.name,
      label: item.level,
      parentIds: item.parentIds
    }
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // 递归Recursion
      current.children = treePermissionConvert(item.children)
    }
    return current
  })
}

/**
 * 权限树Convert字段转换-节点上绑定父节点-父父节点-父父父节点...
 *
 * @param treeData
 * @returns {*}
 */
export function treePermissionHasParentIdsConvert (treeData) {
  return treeData.map(item => {
    const current = {
      name: item.name,
      icon: item.icon,
      key: item.parentIds + ',' + item.id,
      title: item.name,
      scopedSlots: {
        title: 'titleFmt'
      },
      label: item.level
    }
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // 递归Recursion
      current.children = treePermissionHasParentIdsConvert(item.children)
    }
    return current
  })
}
